//
//  HomeViewController.swift
//  InterviewContent
//
//  Created by apple on 2016/12/18.
//  Copyright © 2016年 interviewContent. All rights reserved.
//

import UIKit
import Alamofire


class HomeViewController: UIViewController, UITextFieldDelegate {

    var isPostRequest : Bool = true
    var hasHeader : Bool = false
    var hasPara : Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(scrollerView)
        scrollerView.addSubview(APIcallerLB)
        scrollerView.addSubview(headView)
        headView.addSubview(requesetLB)
        headView.addSubview(lineView)
        headView.addSubview(URLTextField)
        headView.addSubview(URLLineView)
        headView.addSubview(URLLineView2)
        headView.addSubview(requestTypeBtn)
        headView.addSubview(lineView2)
        headView.addSubview(submitBtn)
        headView.addSubview(requestHeaderBtn)
        headView.addSubview(requestParaBtn)
        
        scrollerView.frame = self.view.frame
        APIcallerLB.frame = CGRect(x: 10, y: 10, width: 200, height: 40)
        headView.frame = CGRect(x: 10, y: 50, width: self.view.frame.width - 20, height: 180)
        requesetLB.frame = CGRect(x: 10, y: 10, width: headView.frame.width - 20, height: 40)
        lineView.frame = CGRect(x: 0, y: 51, width: requesetLB.frame.width + 20, height: 0.8)
        URLTextField.frame = CGRect(x: 10, y: 60, width: requesetLB.frame.width, height: 40)
        URLLineView.frame = CGRect(x: 0, y: 101, width: requesetLB.frame.width + 20, height: 0.8)
        URLLineView2.frame = CGRect(x: 0, y: 102, width: requesetLB.frame.width + 20, height: 0.8)
        requestTypeBtn.frame = CGRect(x: 10, y: 110, width: 50, height: 30)
        lineView2.frame = CGRect(x: 10, y: 142, width: 50, height: 0.7)
        submitBtn.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        submitBtn.center = CGPoint(x: self.view.frame.width/2 - 10, y: 180)
        requestHeaderBtn.frame = CGRect(x: 70, y: 110, width: 120, height: 30)
        requestParaBtn.frame = CGRect(x: 200, y: 110, width: 120, height: 30)
        
        
        
        scrollerView.contentSize = CGSize(width: self.view.frame.width, height: 700)
        
    }
    private lazy var scrollerView : UIScrollView = {
        let view = UIScrollView()
        view.backgroundColor = UIColor.darkGray
        return view
    }()
    
    private lazy var APIcallerLB : UILabel = {
        let label = UILabel()
        label.textColor = UIColor.orange
        label.font.withSize(20)
        label.text = "API caller"
        return label
    }()

    private lazy var headView : UIView = {
        let headView = UIView()
        headView.backgroundColor = UIColor.black
        headView.layer.cornerRadius = 10
        headView.layer.shadowOffset = CGSize(width: 0, height: 1)
        headView.layer.shadowOpacity = 4.0
        headView.layer.shadowRadius = 4.0
        headView.layer.shadowColor = UIColor.black.cgColor
        return headView
    }()

    private lazy var requesetLB : UILabel = {
        let label = UILabel()
        label.text = "Ruquest Body"
        label.font.withSize(16)
        label.textColor = UIColor.orange
        return label
    }()
    
    private lazy var lineView : UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor.orange
        return lineView
    }()
    
    private lazy var URLTextField : UITextField = {
        let textField = UITextField()
        textField.layer.borderWidth = 0.7
//        textField.layer.borderColor = UIColor.orange.cgColor
        textField.text = "http://blog.csdn.net/zhonggaorong/article/details/52953793"
        textField.textColor = UIColor.white
        textField.delegate = self
        return textField
    }()
    
    private lazy var URLLineView : UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor.orange
        return lineView
    }()
    
    private lazy var URLLineView2 : UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor.orange
        return lineView
    }()
    
    private lazy var requestTypeBtn : UIButton = {
        let button = UIButton()
        button.titleLabel?.font.withSize(18)
        button.setTitleColor(UIColor.orange, for: UIControlState.normal)
        button.setTitle("post", for: UIControlState.normal)
        button.addTarget(self, action: #selector(HomeViewController.requestType), for: UIControlEvents.touchUpInside)
        return button
    }()
    
    private lazy var lineView2 : UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor.orange
        return lineView
    }()
    
    private lazy var requestHeaderBtn : UIButton = {
        let button = UIButton()
        button.titleLabel?.font.withSize(18)
        button.setTitle("Header", for: UIControlState.normal)
        button.addTarget(self, action: #selector(HomeViewController.addHeaderRequestView), for: UIControlEvents.touchUpInside)
        return button
    }()
    
    private lazy var requestParaBtn : UIButton = {
        let button = UIButton()
        button.titleLabel?.font.withSize(18)
        button.setTitle("Paraer", for: UIControlState.normal)
        button.addTarget(self, action: #selector(HomeViewController.addParaerRequestView), for: UIControlEvents.touchUpInside)
        return button
    }()
    
    private lazy var submitBtn : UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.orange
        button.layer.cornerRadius = 25
        button.setImage(UIImage(named: "tabbar_discover"), for: UIControlState.normal)
        button.addTarget(self, action: #selector(HomeViewController.submitRequet), for: UIControlEvents.touchUpInside)
        return button
    }()
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    func requestType() {
        isPostRequest = !isPostRequest
        requestTypeBtn.setTitle(isPostRequest ? "post" : "get", for: UIControlState.normal)
    }
    
    func submitRequet() {
        if (URLTextField.text?.isEmpty)! {
            let alertController = UIAlertController(title: "title", message: "请输入地址", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "ok", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
            return
        }
        let headerKey = hasHeader ? HeaderView().headerKey : ""
        let headerValue = hasHeader ? HeaderView().headerValue : ""
        let requestHeader:HTTPHeaders = [headerKey : headerValue];
        
        let paraKey = hasPara ? HeaderView().headerKey : ""
        let paraValue = hasPara ? HeaderView().headerValue : ""
        let para = [paraKey : paraValue];
        let mainQueue = DispatchQueue.main;
        
        // 判断post、get请求
        if isPostRequest {
            Alamofire.request(URLTextField.text!,
                              method: .post, parameters: para,
                              encoding: URLEncoding.default, headers: requestHeader).responseJSON(queue:mainQueue, options: .allowFragments) { (response) in
                                
                                print(response)
                                self.presentResentView(data: response.description)
            }
        } else {
            Alamofire.request(URLTextField.text!,
                              method: .get, parameters: para,
                              encoding: URLEncoding.default, headers: requestHeader).responseJSON(queue:mainQueue, options: .allowFragments) { (response) in
                                
                                self.presentResentView(data: response.description)
            }
        }
    }
    
    func presentResentView(data: String) {
        let svc = ResultViewController()
        svc.resuleData = data
        self.navigationController?.pushViewController(svc, animated: true)
    }
    
    // 是否添加请求头
    func addHeaderRequestView() {
        hasHeader = !hasHeader
        if hasHeader {
            requestHeaderBtn.setTitleColor(UIColor.orange, for: UIControlState.normal)
            let headerRequestView : UIView = {
                let view = HeaderView()
                view.isHeader = true
                view.tag = 100
                return view
            }()
            scrollerView.addSubview(headerRequestView)
//            headerRequestView.frame = CGRect(x: 10, y: headView.frame.maxY + 10, width: headView.frame.width, height: 70)
            setupViewHeight(view: headerRequestView)
        } else if (view.viewWithTag(100) != nil) {
            requestHeaderBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
            view.viewWithTag(100)?.removeFromSuperview()
            if (view.viewWithTag(200) != nil) {
                setupViewHeight(view: view.viewWithTag(200)!)
            }
            
        }
    }
    
    // 是否添加请参数
    func addParaerRequestView() {
        hasPara = !hasPara
        if hasPara {
            requestParaBtn.setTitleColor(UIColor.orange, for: UIControlState.normal)
            let headerRequestView : UIView = {
                let view = HeaderView()
                view.isHeader = false
                view.tag = 200
                return view
            }()
            scrollerView.addSubview(headerRequestView)
            setupViewHeight(view: headerRequestView)
        } else if (view.viewWithTag(200) != nil) {
            requestParaBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
            view.viewWithTag(200)?.removeFromSuperview()
            if (view.viewWithTag(100) != nil) {
                setupViewHeight(view: view.viewWithTag(100)!)
            }
        }
    }
    
    func setupViewHeight(view : UIView) {
        if hasHeader && hasPara{
            view.frame = CGRect(x: 10, y: headView.frame.maxY + 210, width: headView.frame.width, height: 160)
        } else {
            view.frame = CGRect(x: 10, y: headView.frame.maxY + 40, width: headView.frame.width, height: 160)
        }
    }
}
